package com.example.demo.utils;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.pojo.Result;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
//    @Override//创建  只执行一次
//    public void init(FilterConfig filterConfig) throws ServletException {
//        Filter.super.init(filterConfig);
//    }

    @Override//实现过滤  执行多次
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        /** 1.
         * 获取请求的URL地址
         * */
        String url = request.getRequestURL().toString();
        System.out.println("url=" + url);

        /** 2.
         * 判断请求的URL是否包含login关键字  包含就要放行
         * */
        if (url.contains("login")) {
            System.out.println("这里是登录操作放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        /** 3.
         * 获取请求头中的token
         * */
        String token = request.getHeader("token");

        /** 4.
         * 判断jwt令牌(token)是否存在,不存在就是未登录
         * */
        //使用spring中的StringUtils工具类,判断token是否有长度
        if (!StringUtils.hasLength(token)) {
            System.out.println("请求token为空");
            Result error = Result.error("NOT_LOGIN", null);
            //手动将对象转为JSON格式
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }

        /** 5.
         * jwt存在
         * 解析token,解析失败返回错误
         * jwt解析失败 证明已经失效
         * */
        try {
            JwtUtils.JwtParse(token);
        } catch (Exception e) {
            e.printStackTrace();
            Result error = Result.error("NOT_LOGIN", null);
            //手动将对象转为JSON格式
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }

        /**
         * 放行
         * */
        filterChain.doFilter(servletRequest,servletResponse);
    }

//    @Override//销毁  只执行一次
//    public void destroy() {
//        Filter.super.destroy();
//    }
}
